<?php
/*
 * @Author: 李明
 * @Date: 2021-08-10 17:29:12
 * @LastEditTime: 2022-01-20 11:37:48
 * @LastEditors: 李明
 * @Description:
 * @FilePath: /CRM2.0-PHP/app/Http/Controllers/admin/PowerController.php
 * @山东壹零贰肆信息科技有限公司
 */

namespace App\Http\Controllers\admin;

use App\Http\Controllers\common\CommonFun;
use App\Http\Controllers\common\LMReturn;
use App\Http\Controllers\Controller;
use App\Models\Power;
use App\Models\Role;
use App\Models\RolePower;
use App\Models\Worker;
use App\Models\WorkerRole;
use Illuminate\Http\Request;
use PhpParser\Node\Expr\AssignOp\Pow;

class PowerController extends Controller
{
    //权限的列表（有树结构）
    public function PowerList(Request $request)
    {
        try { // 接参
            //去验证token值
            $tokenInfo = json_decode($this->verifyTokenLm(), true);
            //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
            if ($tokenInfo['code'] == 400) {
                return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
            }
            //接收前端传递过来的值
            $all = $request->all();
            $worker_id = $tokenInfo['worker_id'];
        } catch (\Throwable $th) {
            return LMReturn::Error('传参发生错误', 'PCPL2');
        }
        if (isset($all['id'])) {
            $role = Role::where('id', $all['id'])->with('powers')->first();
            if (isset($role['powers'])) {
                $powers = json_decode($role['powers'], true);
                $powers_tree = CommonFun::ArrToTreeList($powers, "id", "pid");
                return LMReturn::Success($powers_tree);
            }
        }
        try {
            $worker = Worker::find($worker_id);
            $roles = $worker->roles;
            if (count($roles) != 1) {
                return LMReturn::Error('权限查询出现问题', 'PCPL1');
            }
            $powers = $roles[0]->powers;
            $powers = json_decode($powers, true);
            $powers_tree = CommonFun::ArrToTreeList($powers, "id", "pid");
            return LMReturn::Success($powers_tree);
        } catch (\Throwable $th) {
            return LMReturn::Error('传参发生错误', 'PCPL3');
        }
    }


    //返回这个用户的权限
    public function WorkerPowerList(Request $request)
    {
        //去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        //接收前端传递过来的值
        $all = $request->all();

        $worker_id = $tokenInfo['worker_id'];

        $info = json_decode(Worker::select("power.*")
            ->join("worker_role", "worker.id", "=", "worker_role.worker_id")
            ->join("role", "role.id", "=", "worker_role.role_id")
            ->join("role_power", "role.id", "=", "role_power.role_id")
            ->join("power", "power.id", "=", "role_power.power_id")
            ->where("worker_role.worker_id", "=", $worker_id)
            ->get(), true);
        // dd($info);
        // $info = Success::uniques($info);// 去重
        $info = CommonFun::ArrToTreeList($info, "id", "pid"); // 转成 treelist
        return LMReturn::Success($info);
    }

    //给角色去添加和修改权限
    public function RolePowerSave(Request $request)
    {
        //去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        //接收前端传递过来的值
        $all = $request->all();
        // dd($all);
        //通过传递过来的员工ID来判断，如果能查询到，那么就是添加，反之就是修改
        $info = json_decode(RolePower::where('role_id', $all['role_id'])->get(), true);
        // dd($info);
        if (empty($info)) {
            //这里走添加
            foreach ($all['power'] as $key => $value) {
                $res = RolePower::create([
                    "role_id" => $all['role_id'],
                    "power_id" => $value['power_id']
                ]);
            }
            return LMReturn::sqlRes($res);
        } else {
            //这里是查询出来这个角色现在有权限，所以说是修改
            //先进行删除
            $res = RolePower::where("role_id", $all['role_id'])->delete();
            //进行添加
            //这里走添加
            foreach ($all['power'] as $key => $value) {
                $res = RolePower::create([
                    "role_id" => $all['role_id'],
                    "power_id" => $value['power_id']
                ]);
            }
            return LMReturn::sqlRes($res);
        }
    }

    public function savePower(Request $request)
    {
        //去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        //接收前端传递过来的值
        $all = $request->all();
        if (isset($all['name'])) {
            $name = $all['name'];
        } else {
            return LMReturn::Error('缺少必传参数', 'PC001');
        }
        if (isset($all['pid'])) {
            $pid = $all['pid'];
        } else {
            return LMReturn::Error('缺少必传参数', 'PC002');
        }
        if (isset($all['id'])) { //修改
            try {
                $power = Power::where('id', $all['id'])->first();
                $res = $power->update(
                    [
                        'name' => $name,
                        'pid' => $pid,
                    ]
                );
                return LMReturn::Success($power, '成功修改权限');
            } catch (\Throwable $th) {
                return LMReturn::Error('网络错误', 'PC004');
            }
        } else { // 添加
            try {
                $power = Power::create(
                    [
                        'name' => $name,
                        'pid' => $pid,
                    ]
                );
                //加上之后接着给超级管理员加上
                $role = Role::where('id', '1')->first();
                $role->powers()->syncWithoutDetaching($power->id);
                $role->save();
                return LMReturn::Success($power, '成功添加权限');
            } catch (\Throwable $th) {
                return LMReturn::Error('网络错误', 'PC003');
            }
        }
    }
    /**
     * @description: 管理员权限错乱时使用
     * @param {*}
     * @return {*}
     */
    public function AdminPowerAdd(Request $request)
    {
        $power_list = Power::all();
        try {
            $id_list = [];
            foreach ($power_list as $power) {
                $id_list[] = $power->id;
            }
            $role = Role::find(1);
            $role->powers()->syncWithoutDetaching($id_list);
            return LMReturn::Success($role->powers()->get(), '重置超级管理员权限成功');
        } catch (\Throwable $th) {
            return LMReturn::Error('错误', 'PC005');
        }
    }
    /**
     * @description: 删除接口，平时不要调用
     * @param {Request} $request
     * @return {*}
     */
    public function deletePower(Request $request)
    {
        //去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        $all = $request->all();
        $power_id = $all['power_id'];
        $power = Power::find($power_id);
        $power_list = [];
        $power_list[] = $power;
        $power_list = $this->queryAllSumPower($power, $power_list);
        if ($tokenInfo['worker_id'] == '17') {
            foreach ($power_list as $sum_power) {
                $sum_power->delete();
            }
            return LMReturn::Success($power_list, '成功删除');
        } else {
            return LMReturn::Error('接口未开放');
        }
    }
    public function queryAllSumPower($power, $power_list)
    {
        $power_sum_list = Power::where('pid', $power->id)->get();
        foreach ($power_sum_list as $sum_power) {
            $power_list[] = $sum_power;
            $power_list = $this->queryAllSumPower($sum_power, $power_list);
        }
        return $power_list;
    }
}
